package com.example.changecode;

import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.SelectionModel;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.util.Consumer;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;

import java.util.List;

public class WordSelectAction extends AnAction {

    @Override
    public void actionPerformed(AnActionEvent e) {
        Editor editor = e.getData(CommonDataKeys.EDITOR);
        Project project = e.getData(CommonDataKeys.PROJECT);
        Document document = editor.getDocument();
        SelectionModel selectionModel = editor.getSelectionModel();
        String text = selectionModel.getSelectedText(false);
        JBPopupFactory instance = JBPopupFactory.getInstance();
        if (StringUtils.isEmpty(text)) {
            return;
        }
        List<String> words = Conversion.transFrom(text);
        Consumer<String> consumer = s -> selText(editor, project, document, s);

        instance.createPopupChooserBuilder(words)
                .setTitle("words")
                .setItemChosenCallback(consumer).createPopup().showInBestPositionFor(editor);
    }

    private void selText(Editor editor, Project project, Document document, String s) {
        SelectionModel selectionModel = editor.getSelectionModel();
        int start = selectionModel.getSelectionStart();
        int end = selectionModel.getSelectionEnd();
        Runnable runnable = () -> document.replaceString(start, end, s);

        WriteCommandAction.runWriteCommandAction(project, runnable);
        selectionModel.removeSelection();
    }

    @Override
    public void update(@NotNull AnActionEvent e) {
        Editor editor = e.getData(CommonDataKeys.EDITOR);
        Project project = e.getData(CommonDataKeys.PROJECT);
        e.getPresentation().setVisible(project != null && editor != null && editor.getSelectionModel().hasSelection());
    }
}
